package cn.it58.gooditname.listeners

import cn.it58.gooditname.services.UpdateService
import cn.it58.gooditname.services.UpdateInfo
import cn.it58.gooditname.services.VersionService
import com.intellij.ide.BrowserUtil
import com.intellij.notification.NotificationAction
import com.intellij.notification.NotificationGroupManager
import com.intellij.notification.NotificationType
import com.intellij.openapi.actionSystem.AnActionEvent
import com.intellij.openapi.project.Project
import com.intellij.openapi.startup.StartupActivity

/**
 * 插件启动监听器
 */
class StartupListener : StartupActivity {
    
    override fun runActivity(project: Project) {
        // 延迟5秒后检查更新和公告，避免影响IDEA启动速度
        Thread {
            Thread.sleep(5000)
            checkAnnouncementAndUpdates(project)
        }.start()
    }
    
    private fun checkAnnouncementAndUpdates(project: Project) {
        try {
            val updateService = UpdateService()
            val updateInfo = updateService.checkForUpdates()
            
            if (updateInfo != null) {
                // 显示公告通知
                if (updateInfo.announcement.isNotBlank()) {
                    showNotification(
                        project,
                        "📢 GoodName 公告：${updateInfo.announcement}",
                        NotificationType.INFORMATION
                    )
                }
                
                // 检查是否有新版本，使用VersionService进行智能比较
                if (VersionService.hasNewVersion(updateInfo.latestVersion)) {
                    val currentVersion = VersionService.getCurrentVersion()
                    showUpdateNotification(
                        project,
                        "🆕 发现新版本 ${updateInfo.latestVersion}（当前：${currentVersion}）：${updateInfo.description}",
                        updateInfo
                    )
                }
            }
        } catch (e: Exception) {
            // 静默失败，不影响用户体验
        }
    }
    
    private fun showNotification(project: Project, content: String, type: NotificationType) {
        val notificationGroup = NotificationGroupManager.getInstance()
            .getNotificationGroup("GoodName Notifications")
        
        notificationGroup.createNotification(content, type)
            .notify(project)
    }
    
    private fun showUpdateNotification(project: Project, content: String, updateInfo: UpdateInfo) {
        val notificationGroup = NotificationGroupManager.getInstance()
            .getNotificationGroup("GoodName Notifications")
        
        val notification = notificationGroup.createNotification(content, NotificationType.INFORMATION)
        
        // 添加"前往更新"按钮
        notification.addAction(object : NotificationAction("🔄 前往更新") {
            override fun actionPerformed(e: AnActionEvent, notification: com.intellij.notification.Notification) {
                // 跳转到IDEA插件市场的GoodName插件页面
                val pluginMarketUrl = "jetbrains://idea/plugins/page?id=cn.it58.goodname"
                BrowserUtil.browse(pluginMarketUrl)
                notification.expire()
            }
        })
        
        // 添加"查看详情"按钮
        notification.addAction(object : NotificationAction("📋 查看详情") {
            override fun actionPerformed(e: AnActionEvent, notification: com.intellij.notification.Notification) {
                val detailMessage = """
                    🎉 GoodName 新版本发布！
                    
                    📢 公告：${updateInfo.announcement}
                    
                    🔖 当前版本：${VersionService.getCurrentVersion()}
                    🆕 最新版本：${updateInfo.latestVersion}
                    📝 更新说明：${updateInfo.description}
                    
                    💡 点击"前往更新"按钮可直接跳转到插件市场进行更新
                """.trimIndent()
                
                javax.swing.JOptionPane.showMessageDialog(
                    null,
                    detailMessage,
                    "GoodName 更新详情",
                    javax.swing.JOptionPane.INFORMATION_MESSAGE
                )
            }
        })
        
        // 添加"稍后提醒"按钮
        notification.addAction(object : NotificationAction("⏰ 稍后提醒") {
            override fun actionPerformed(e: AnActionEvent, notification: com.intellij.notification.Notification) {
                notification.expire()
            }
        })
        
        notification.notify(project)
    }
} 